let arr = [
    { id: 1, name: '部门1', pid: 0 },
    { id: 2, name: '部门2', pid: 1 },
    { id: 3, name: '部门3', pid: 1 },
    { id: 4, name: '部门4', pid: 3 },
    { id: 5, name: '部门5', pid: 4 },
    { id: 6, name: '部门6', pid: 0 },
]

function get_tree(arr) {
    const list = []

    arr.forEach(element => {
        //? 搜索出当前元素有哪些孩子
        const children_arr = arr.filter(ele => {
            return element.id === ele.pid
        })
        //? 如果有孩子
        if (children_arr.length > 0) {
            //? 往当前元素中添加children字段
            element.children = children_arr
        }
        //? 此元素是根元素 直接入数组
        if (element.pid === 0) {
            list.push(element)
        }
    });

    return list
}
console.log(get_tree(arr));
